package server

import java.io._
import java.util.zip._

class CompressedContent(identifier:String, content:String) extends Content(identifier, CompressedContent.compressData(content)){
	
	override def getContent():String = {
		CompressedContent.uncompressData(super.getContent)
	}
}

object CompressedContent{	
	def compressData(data:String) : String = {
	  println("Compressing: " +  data)
	  var input = data.getBytes
	  
	  var compresser = new Deflater();
	  compresser.setInput(input);
	  compresser.finish();
	  
	  var bos = new ByteArrayOutputStream(input.length)

	  // Compress the data
	  var buf = new Array[Byte](1024)
	  while (!compresser.finished()) {
		    var count = compresser.deflate(buf)
		    bos.write(buf, 0, count);
	  }
	  bos.close();
	  
	  // Get the compressed data
	  var compressedData = bos.toByteArray();
	  var compressedString = new String(compressedData)
	  
	  print("Compressed data: "+compressedString)
	  return compressedString
	}
  
  def uncompressData(data: String) : String = {
	  //println("Uncompressing: " +  data)
	  var input = data.getBytes
	  var decompresser = new Inflater()
	  decompresser.setInput(input) //, 0, compressedDataLength);
	  var result = new Array[Byte](100)
	  var resultLength = decompresser.inflate(result)
	  decompresser.end();
	
	  var outputString = new String(result, 0, resultLength, "UTF-8");
	  //println("Uncompressed: " + outputString)
	  
	  return outputString
	}
}